#ifndef IGETTERMESSAGE_H
#define IGETTERMESSAGE_H

#include <Active.h>

/** Template class to implement getter messages, i.e. task that gives back a result.
 *  
 * It could also be used as a syncronization point: the main thread can wait for the result.
 */
template <typename T>
class IGetterMessage: public Active::Message
{
  public:
    IGetterMessage() {};
  
    ///Entry point. Virtual because in certain cases, mutex could be handlded in a more efficient way.
    virtual void Execute()
    {
      {
	boost::mutex::scoped_lock l(m_mutex);
	OnExecuting();
	m_done=true;
      }
      m_cond.notify_one();
    };
    
    
    T get() 
    {
      boost::mutex::scoped_lock l(m_mutex);
      while (!m_done)
      {//while to avoid spurious wake up
	m_cond.wait(l);
      }
      return getResult();
    }
    
private :
  /** Virtual function that must be implemented by child classes. 
   * 
   * Here the real action should be implemented. 
   * This method is executed in the context of the ActiveObject's thread
   */
  virtual void OnExecuting()=0;
  
  /** Virtual getter function that must be implemented by child classes. 
   * 
   * Here goes the implementation for giving back to the caller the result of
   * the specific job.
   * @return Template return type, defined by child's implementation.
   */
  virtual T getResult()=0;
  
private:
  
  /** Condition variable to notify caller thread, waiting for job execution. */
  mutable boost::condition_variable m_cond;
  
  /** Mutex that protect both m_done and other variables used by OnExecuting() and getResult(). 
  * SubOptimal, but simplify implementation  */
  mutable boost::mutex m_mutex;

  /** Bool member that hold the status of the task.
   * True when the task is completed. */
  bool m_done;
  
};

#endif //GETTERMESSAGE_H